package com.gzy.cs5.Repository;

import com.gzy.cs5.exception.BusinessException;
import com.gzy.cs5.exception.ErrorCode;
import com.gzy.cs5.model.InventoryItem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MemoryInventoryRepository implements InventoryRepository {
    private final Map<String, InventoryItem> inventoryMap = new HashMap<>();

    @Override
    public void addItem(InventoryItem item) throws BusinessException {
        if (inventoryMap.containsKey(item.getItemId())) {
            throw new BusinessException(ErrorCode.ITEM_NOT_FOUND, "库存项已存在: " + item.getItemId());
        }
        inventoryMap.put(item.getItemId(), item);
    }

    @Override
    public void removeItem(String itemId) throws BusinessException {
        if (!inventoryMap.containsKey(itemId)) {
            throw new BusinessException(ErrorCode.ITEM_NOT_FOUND, "库存项未找到: " + itemId);
        }
        inventoryMap.remove(itemId);
    }

    @Override
    public List<InventoryItem> getAllItems() {
        return new ArrayList<>(inventoryMap.values());
    }

    @Override
    public InventoryItem getItemById(String itemId) {
        return inventoryMap.get(itemId);
    }

    @Override
    public void updateItemQuantity(String itemId, int quantity) throws BusinessException {
        InventoryItem item = inventoryMap.get(itemId);
        if (item == null) {
            throw new BusinessException(ErrorCode.ITEM_NOT_FOUND, "库存项未找到: " + itemId);
        }
        item.setQuantity(quantity);
    }
}
